#user/bin/env python3
# -*- coding: utf-8 -*-
# -- anth bluedolphi ---
# !/user/bin/env python3
# -*- coding: utf-8 -*-
# -- anth bluedolphi ---
import json
import os

import datetime
import pandas
import time

import pandas as pd
import requests
from pip._vendor.requests.structures import CaseInsensitiveDict
from tqdm import tqdm

from spider.AIYZ.AIYZSpirder import AIYZBaseSpider
from util.DateUtil import getDateTimeFromString, getDeltaDaysWithNow
from util.HttpUtil.BaseHttpUtil import BaseHttpUtil
from util.HttpUtil.EncodeingUtil import url_encode
from util.XlsUtil import loadXlsGetSheel
from util.imageCode import VerificationCode
import threading


class AIYZSpider(AIYZBaseSpider):
    host = "www.aiyouzhan.cn"
    gasStationCode = ""
    gasStationName = ""
    gasStation = None
    account = ""
    password = ""

    loginUrl = "https://api.aiyouzhan.cn/api/enterprise/enterprise/login";
    randcodeUrl = 'https://api.aiyouzhan.cn/api/common/getImageCaptche'
    token = '';
    activityTypes = ["新关注", "成功推广用户", "手工发券", "微信分享", "加油返券", "扫码送券", "推广会员激活", "充值领券",
                     "加油推广送券"]  # type = 1新关注 2成功推广用户; 3手工发券; 4微信分享; 5加油返券; 6扫码送券; 7推广会员激活; 8充值领券; 9加油推广送券;

    def __init__(self,host="enterprise.aiyouzhan.cn"):
        self.host = host
        super().__init__(self.host)

        self.header = {
            'Host': 'api.aiyouzhan.cn',
            'Connection': 'keep-alive',
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Origin': 'https://%s' %(self.host),
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
            'Referer': 'https://%s/index.html' % (self.host),
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9',
        }

    def getRandCode(self):
        _headers = CaseInsensitiveDict([
            ('Accept', '*/*'),
            ('Accept-Encoding', 'gzip, deflate'),
            ('Accept-Language', 'zh-CN,zh;q=0.9'),
            ('Connection', 'keep-alive'),
            ('Host', 'api.aiyouzhan.cn'),
            ('Origin', 'https://%s' % self.host),
            ('Referer', 'https://%s/' % self.host),
            ('User-Agent', self.AGENT_STRING)])

        url = "%s?t=%s" % (self.randcodeUrl, int(time.time()))
        rep = self.get(url, headers=_headers);
        json = rep.json()
        if (json['code'] == 1):
            image = json['data']['image']
            image = str(image).replace("data:image/png;base64,", "")
            # print(image)
            randCodeImagePath = "code.png"
            self.saveBase64Image(image, fileName=randCodeImagePath)
            verificationCode = VerificationCode().getVerificationCode(randCodeImagePath)
            return json['data']['token'], verificationCode

    def get_statistical_point(self,dateType=30,startDate="",endDate=""):
        baseUrl = "https://%s/api/point/enterprise/user-point-log/get-statistical-point?t=%s&dateType=%s&startDate=%s&endDate=%s&token=%s" % (self.host,
                                                                                                            int(time.time()),dateType,
                                                                                                            startDate,
                                                                                                            endDate,
                                                                                                            self.token)
        json = self.get(baseUrl,headers=self.header).json()
        print(json)
        if json is None or json["data"] is None:
            return None

        return  json["data"]

    def get_yestoday_statistical_point(self):
        text=""
        json = self.get_statistical_point()
        print(json["axisData"])
        index = len(json["axisData"][0]["data"]) - 2
        text = "%s ：\n" % json["axisData"][0]["data"][index]
        for i in range(4):
            text +="  %s:%s\n" % (json["seriesData"][i]["name"],json["seriesData"][i]["lineData"][index])
        print(text)
        return text

    def isLogined(self):
        if self.getEnterpriseInfo() is None:
            return False
        return True

    def login(self, gasStationCode, username, password):
        imgToken, code = self.getRandCode()
        self.gasStationCode = gasStationCode;
        data = url_encode({
            'gasStationCode': gasStationCode,
            'username': username,
            'password': password,
            'code': code,
            'imgToken': imgToken,
        })
        rep = self.post(self.loginUrl, data=data, headers=self.header)

        json = rep.json()
        if (json['code'] == 1):
            self.token = json['data']['token']
            self.header.update([("Authorization", "Bearer %s" % self.token)])
            # print("token = ", self.token)
        else:
            print("登录失败，请检查油站编号、用户名、密码 有没有错误!")

    def setToken(self, token):
        self.token = token
        self.header.update([("Authorization", "Bearer %s" % self.token)])
    def searchOrder(self, status=2, pageSize=100,operatorId='', oilTypeId='',
                                userId='', startDate="2019-09-01 00:00:00", endDate="2019-09-10 23:59:59"):
        baseUrl = "https://%s/api/gas/enterprise/searchOrder?status=%s&startDate=%s&endDate=%s&token=%s" % (self.host,
        status, startDate, endDate, self.token)
        list = self.getRowsFromUrl(baseUrl, pageSize)

        return list


    def search_all_memeber_info(self,  pageSize=20):
        baseUrl = "https://%s/api/member/enterprise/userPageList?token=%s" % (self.host, self.token)
        list = self.getRowsFromUrl(baseUrl, pageSize)
        return list

    def getUserRecharge(self,pageSize=50):
        baseUrl = "https://%s/api/account/enterprise/recharge/getUserRechargeAction?token=%s" % (self.host, self.token)
        list = self.getRowsFromUrl(baseUrl, pageSize)
        return list
    def searchOrderAndSaveToXls(self, saveFileName="order.xlsx", size=90, status=2, operatorId='', oilTypeId='',
                                userId='', startDate="2019-09-01 00:00:00", endDate="2019-09-10 23:59:59"):
        list = self.searchOrder(status=status,pageSize=size,  operatorId=operatorId, oilTypeId=oilTypeId,
                                userId=userId, startDate=startDate, endDate=endDate)
        titles = {"wxName": "用户", "oilTypeName": "油品名", "gunName": "油枪名", "operatorName": "加油员名称", "amount": "订单金额",
                  "payAmount": "实收金额", "couponAmount": "优惠券金额", "deductAmount": "立减金额", "arriveAmount": "到账金额",
                  "deductionPoint": "积分抵扣", "disAmount": "会员折扣", "orderTime": "支付时间", "createTime": "创建时间",
                  "payMethodName": "支付方式", "statusName": "状态名", "userId": "用户编号"}
        info = self.getEnterpriseInfo()
        saveFileName = "%s\\upload\\%s 加油订单.xlsx" % (
            os.path.dirname(os.path.realpath(__file__)), info["name"])
        saveFileName = saveFileName.replace("\\spider\\AIYZ", "")
        self.saveListToXls(saveFileName,titles,list,"订单")
        print("\n加油订单数据采集完成！")

        return saveFileName



    def searchOrderAndSaveToXls_noThread(self, saveFileName="order.xlsx", size=90, status=2, operatorId='',
                                         oilTypeId='',
                                         userId='', startDate="2019-09-01 00:00:00", endDate="2019-09-10 23:59:59"):
        token = self.token;
        wb1, sheet = loadXlsGetSheel(saveFileName, '加油订单明细')

        # titleArray = ["序号","编号","用户编号","车牌号","手机","微信名","企业编号","油站编号 ","油品名称","操作员","操作用户编号","操作员名称","materialId","油品编号","油站名称","油枪编号","油枪名称","金额","优惠金额","立减金额","订单号","状态 ","支付编号","支付方式","订单时间","状态名称","用户信息","折扣","折扣金额","支付金额","disAmount","会员等级","balance","扣减点","扣除额","到帐金额","创建时间"]
        titleArray = ["序号", "用户", "油品名", "油枪名", "加油员名称", "订单金额", "实收金额", "优惠券金额", "立减金额", "到账金额", "积分抵扣", "会员折扣", "手续费",
                      "支付时间", "创建时间", "支付方式", "状态名", "用户编号"]
        i = 0
        for s in titleArray:
            sheet.cell(row=1, column=i + 1, value=s)
            i += 1
        row = 2
        currentPage = 1
        while True:
            data = url_encode({
                'page': currentPage,
                'size': size,
                'token': token,
                'status': status,
                'operatorId': operatorId,
                'oilTypeId': oilTypeId,
                'userId': userId,
                'startDate': startDate,
                'endDate': endDate,
                't': int(time.time()),
            })
            url = "https://api.aiyouzhan.cn/api/gas/enterprise/searchOrder?%s" % (data)
            rep = self.get(url, headers=self.header)
            rep.encoding = 'utf-8'
            json1 = rep.json()
            if json1['code'] == 1:

                totalPage = self.getTotalPageByJson(json1, size)

                # print('当前是 第%s页/共%s页 共%s条 完成:%s' % (currentPage,totalPage,totalRows,currentPage/totalPage))
                for json2 in json1['data']['rows']:
                    # "序号",
                    sheet.cell(row=row, column=1, value=row - 1)
                    # "用户",
                    sheet.cell(row=row, column=2, value=json2['wxName'])
                    # "油品名",
                    sheet.cell(row=row, column=3, value=json2['oilTypeName'])
                    # "油枪名",
                    sheet.cell(row=row, column=4, value=json2['gunName'])
                    # "加油员名称",
                    sheet.cell(row=row, column=5, value=json2['operatorName'])
                    # "订单金额"
                    sheet.cell(row=row, column=6, value=json2['amount'])
                    # "实收金额"
                    sheet.cell(row=row, column=7, value=json2['payAmount'])
                    # 优惠券金额
                    sheet.cell(row=row, column=8, value=json2['couponAmount'])
                    # "立减金额"
                    sheet.cell(row=row, column=9, value=json2['deductAmount'])
                    # 到帐金额
                    sheet.cell(row=row, column=10, value=json2['arriveAmount'])
                    # "积分抵扣"
                    sheet.cell(row=row, column=11, value="")
                    # "会员折扣"
                    sheet.cell(row=row, column=12, value=json2['precentAmount'])
                    # "手续费",
                    sheet.cell(row=row, column=13, value="")
                    ##  "支付时间",
                    sheet.cell(row=row, column=14, value=json2['orderTime'])
                    ## "创建时间",
                    sheet.cell(row=row, column=15, value=json2['createTime'])
                    ## "支付方式",
                    sheet.cell(row=row, column=16, value=json2['payMethodName'])
                    ##  "状态名"
                    sheet.cell(row=row, column=17, value=json2['statusName'])
                    ##  "用户编号"
                    sheet.cell(row=row, column=18, value=json2['userId'])

                    row += 1

                self.view_bar('加油订单数据采集 ', currentPage, totalPage)
                currentPage += 1
                if currentPage > totalPage:
                    break;

            else:
                break;
        wb1.save(saveFileName)
        print("\n加油订单数据采集完成！")

    def searchOrderAndSaveToXlsByLevelId(self, saveFileName="order.xlsx", leveId="", size=90, status=2, operatorId='',
                                         oilTypeId='',
                                         userId='', startDate="2019-09-01 00:00:00", endDate="2019-09-10 23:59:59"):
        if leveId.__eq__(""):
            return
        level_users = self.getUsersByLeveId(leveId)
        level_users_id = []
        for user in level_users:
            level_users_id.append(user["id"])
        print(level_users_id)
        token = self.token;
        wb1, sheet = loadXlsGetSheel(saveFileName, '加油订单明细')

        # titleArray = ["序号","编号","用户编号","车牌号","手机","微信名","企业编号","油站编号 ","油品名称","操作员","操作用户编号","操作员名称","materialId","油品编号","油站名称","油枪编号","油枪名称","金额","优惠金额","立减金额","订单号","状态 ","支付编号","支付方式","订单时间","状态名称","用户信息","折扣","折扣金额","支付金额","disAmount","会员等级","balance","扣减点","扣除额","到帐金额","创建时间"]
        titleArray = ["序号", "用户", "油品名", "油枪名", "加油员名称", "订单金额", "实收金额", "优惠券金额", "立减金额", "到账金额", "积分抵扣", "会员折扣", "手续费",
                      "支付时间", "创建时间", "支付方式", "状态名", "用户编号"]
        i = 0
        for s in titleArray:
            sheet.cell(row=1, column=i + 1, value=s)
            i += 1
        row = 2
        currentPage = 1
        while True:
            data = url_encode({
                'page': currentPage,
                'size': size,
                'token': token,
                'status': status,
                'operatorId': operatorId,
                'oilTypeId': oilTypeId,
                'userId': userId,
                'startDate': startDate,
                'endDate': endDate,
                't': int(time.time()),
            })
            url = "https://api.aiyouzhan.cn/api/gas/enterprise/searchOrder?%s" % (data)
            rep = self.get(url, headers=self.header)
            rep.encoding = 'utf-8'
            json1 = rep.json()
            if json1['code'] == 1:

                totalPage = self.getTotalPageByJson(json1, size)

                # print('当前是 第%s页/共%s页 共%s条 完成:%s' % (currentPage,totalPage,totalRows,currentPage/totalPage))
                for json2 in json1['data']['rows']:
                    # 不在会员等级中，跳过。

                    if json2["userId"] not in level_users_id:
                        continue
                    # "序号",
                    sheet.cell(row=row, column=1, value=row - 1)
                    # "用户",
                    sheet.cell(row=row, column=2, value=json2['wxName'])
                    # "油品名",
                    sheet.cell(row=row, column=3, value=json2['oilTypeName'])
                    # "油枪名",
                    sheet.cell(row=row, column=4, value=json2['gunName'])
                    # "加油员名称",
                    sheet.cell(row=row, column=5, value=json2['operatorName'])
                    # "订单金额"
                    sheet.cell(row=row, column=6, value=json2['amount'])
                    # "实收金额"
                    sheet.cell(row=row, column=7, value=json2['payAmount'])
                    # 优惠券金额
                    sheet.cell(row=row, column=8, value=json2['couponAmount'])
                    # "立减金额"
                    sheet.cell(row=row, column=9, value=json2['deductAmount'])
                    # 到帐金额
                    sheet.cell(row=row, column=10, value=json2['arriveAmount'])
                    # "积分抵扣"
                    sheet.cell(row=row, column=11, value="")
                    # "会员折扣"
                    sheet.cell(row=row, column=12, value=json2['precentAmount'])
                    # "手续费",
                    sheet.cell(row=row, column=13, value="")
                    ##  "支付时间",
                    sheet.cell(row=row, column=14, value=json2['orderTime'])
                    ## "创建时间",
                    sheet.cell(row=row, column=15, value=json2['createTime'])
                    ## "支付方式",
                    sheet.cell(row=row, column=16, value=json2['payMethodName'])
                    ##  "状态名"
                    sheet.cell(row=row, column=17, value=json2['statusName'])
                    ##  "用户编号"
                    sheet.cell(row=row, column=18, value=json2['userId'])

                    row += 1

                self.view_bar('加油订单数据采集 ', currentPage, totalPage)
                currentPage += 1
                if currentPage > totalPage:
                    break;

            else:
                break;
        wb1.save(saveFileName)
        print("\n加油订单数据采集完成！")

    def setUserLevel(self, userId, levelId, ):
        """
        设置用户等级
        :param userId: 用户ID
        :param levelId: 等级ID
        """
        url = 'https://api.aiyouzhan.cn/api/member/enterprise/updateUserLevel?token=%s&t=%s' % (
            self.token, int(time.time()))
        data = url_encode({
            'userIds': userId,
            'levelId': levelId,
            'token': self.token,
        })
        spider = BaseHttpUtil(self.host)
        rep = spider.post(url, data=data, headers=self.header);
        spider.http.close()

    def getUsersByLeveId(self, levelId):
        """
        取得等级下的所有会员信息
        :param levelId:
        """
        baseUrl = "https://api.aiyouzhan.cn/api/member/enterprise/getUserLevelReport?level=%s&minCost=&maxCost=&userId=&min=&max=&startDate=&token=%s&t=%s" % (
            levelId, self.token, int(time.time()))
        rows = self.getRowsFromUrl(baseUrl, pageSize=100)
        return rows

    def get_tickets(self):
        baseUrl = "https://%s/api/union/enterprise/ticket/getTicket?token=%s" % (self.host,self.token)
        rows = self.getRowsFromUrl(baseUrl, pageSize=100)
        return rows

    ActivityTicketStatus = ["已禁用","启用","已使用","已过期",'已发放']
    def getActivityTicketCount(self, activityId, status, startTime, endTime):
        baseUrl = "https://%s/api/union/enterprise/ticket/getActivityTicketPage?token=%s&activityId=%s&status=%s&startTime=%s&endTime=%s" % (
        self.host, self.token, activityId, status, startTime, endTime)
        return self.getTotolRowsFromUrl(baseUrl)

    #取得异业联盟的营销活动列表
    def get_union_activity_list(self,name="",status=""):
        baseUrl="https://%s/api/union/enterprise/activity/pageList?name=%s&status=%s&token=%s" % (self.host,name,status,self.token)
        list=self.getRowsFromUrlByNoThread(baseUrl)
        return list

    def get_union_activity_list_info(self,startTime,endTime,name="",status=""):
        rows = self.get_union_activity_list()
        info ="异业券活动统计：\n 时间：%s-%s\n" %(startTime,endTime)
        for o in rows:
            id, name = o['id'], o['name']
            str = '\n%s:\n  ' % name
            for statuts in self.ActivityTicketStatus:
                count = self.getActivityTicketCount(id, self.ActivityTicketStatus.index(statuts), startTime,
                                                      endTime)
                str += '  %s:%s张  ' % (statuts, count)
            info+=str
        return info


    def getActivityTicketList(self,activityId,status,startTime,endTime):
        baseUrl = "https://%s/api/union/enterprise/ticket/getActivityTicketPage?token=%s&activityId=%s&status=%s&startTime=%s&endTime=%s"% (self.host, self.token,activityId,status,startTime,endTime)



    def getOperatorUsers(self):
        baseUrl="https://%s/api/enterprise/enterprise/operator-user/page-list?token=%s" % (self.token)
        rows = self.getRowsFromUrlByNoThread(baseUrl)
        return rows


    def get_Used_Tickets_by_date(self, aDay):
        rows = self.get_tickets()
        list = []

        for o in rows:
            if o["useTime"] is None or not str(o["useTime"]).__contains__(aDay):
                continue
            list.append(o)
        return list

    def save_used_tickets_by_date_to_xls(self, aDay):
        info = self.getEnterpriseInfo()
        print(info)
        list = self.get_Used_Tickets_by_date(aDay)

        titles = {'id': '优惠券编号', 'userId': '用户编号', 'title': '优惠名称', 'useTime': '使用时间', 'nickName': '用户昵称',
                  'activityName': '活动名称'}

        saveFileName = "%s\\upload\\[%s]%s 洗车券%s张.xlsx" % (
        os.path.dirname(os.path.realpath(__file__)), aDay, info["name"], len(list))
        saveFileName = saveFileName.replace("\\spider\\AIYZ", "")
        self.saveListToXls(saveFileName, titles, list, "洗车券")

        return saveFileName

    def get_total_used_tickets_by_date(self, aDay):
        list = self.get_Used_Tickets_by_date(aDay)
        if list is None :
            return 0
        return len(list)

    def get_total_used_tickets_by_date_with_Str(self,aDay):
        info = self.getEnterpriseInfo()
        print(info["name"])
        total = self.get_total_used_tickets_by_date(aDay)
        return "【%s】%s 使用%s张洗车券 " %(aDay,info["name"],total)

    def getListShift(self, startTime, endTime):
        url = "https://api.aiyouzhan.cn/api/gas/enterprise/shift/getListShift"
        page = 1
        pageSize = 1000
        data = url_encode(
            {"page": page,
             "size": pageSize,
             "startTime": startTime,
             "endTime": endTime,
             "token": self.token,
             "t": int(time.time())
             }
        )

        rep = self.post(url, data, headers=self.header)
        # print(rep.text)
        json1 = rep.json()
        list = []
        if json1["code"] == 1:
            list = json1["data"]["rows"]
        return list

    def getDetailsShift(self, shiftId):
        url = "https://api.aiyouzhan.cn/api/gas/enterprise/shift/DetailsShift?t=%s" % int(time.time())
        data = url_encode(
            {"shiftId": shiftId,
             "token": self.token,
             }
        )
        rep = self.post(url, data, headers=self.header)
        # print(rep.text)
        json1 = rep.json()

        if json1["code"] == 1:
            return json1["data"]
        return None

    def get_activityInfo_by_name(self, activity_name, type="", isGoing=""):
        url = "https://%s/api/coupon/enterprise/activity/page-list?name=%s&type=%s&isGoing=%s&token=%s" % (self.host,
        activity_name, type, isGoing, self.token)
        rows = self.getRowsFromUrlByNoThread(url)
        for o in rows:
            if str(o["name"]).__eq__(activity_name):
                return o
        return None

    def searchUsers(self,keyword):
        url="https://%s/api/member/enterprise/searchUser?keyword=%s&token=%s&t=%s" % (self.host,keyword,self.token,int(time.time()))
        print(url)
        rep=self.get(url,headers=self.header)
        if rep.text.__contains__('"rows":'):
            json1 = rep.json()
            return json1["data"]["rows"]
        elif rep.text.__contains__('"data":[{'):
            json1 = rep.json()
            return json1["data"]

    def get_user_coupons(self,userId,status=1):
        url="https://%s/api/coupon/enterprise/coupon/page-list?status=%s&userId=%s&token=%s" %(self.host,status,userId,self.token)
        rows=self.getRowsFromUrlByNoThread(baseUrl=url)
        return rows


    def get_activity_id(self, activity_name, type="", isGoing=""):
        o = self.get_activityInfo_by_name(activity_name, type=type, isGoing=isGoing)
        if o is None:
            return None
        return o["id"]

    def setLevelRuleIsBlankUsersToLevelRule(self, levelName="普通会员"):
        """
        设置等级为空白到某个等级
        :param levelName:  等级名称
        """
        levelId = self.getLevelRuleIdByName(levelName)
        if levelId is None:
            print('会员等级名称 %s 不存在' % (levelName))
            return

        userIds = []
        baseUrl = 'https://api.aiyouzhan.cn/api/member/enterprise/getUserLevelReport?token=%s' % (self.token)
        pageSize = 20
        page = 1
        print('-------------------  设置等级为空白用户为等级%s  ------------------- ' % levelName)
        while True:
            url = "%s&page=%s&size=%s&t=%s" % (
                baseUrl, page, pageSize, int(time.time()))
            json1 = self.getJsonByUrlWithGet(url)
            totalPages = self.getTotalPageByJson(json1, pageSize)
            # 如果访问出错就退出

            if json1 is None and json1['code'] != 1:
                print('访问出错就退出')
                break;
            print('------------- 共%s页，处理第%s页------------- ' % (totalPages, page))
            for o in json1['data']['rows']:
                # { "id": "", "userId": "", "username": "~zZ", "phone": "XXXXX", "carLicenseNo": "XXX-FGIY4", "totalCost": 95.01, "lastMonthCost": 0.0, "thisMonthCost": 0.0, "levelId": "X", "levelName": "LV2", "adjustLevelId": null, "adjustLevelName": null, "remark": null}
                if o['levelName'] is not None and o['levelName'] != "":
                    # print("用户：%s       等级:%s" % (o['username'], o['levelName']))
                    continue
                else:
                    print("设置用户：%s      当前等级:%s       等级:%s" % (o['username'], o['levelName'], levelName))
                    self.setUserLevel(o["userId"], levelId)

            page += 1
            if page > totalPages:
                break;
        print('-------------------  设置等级为空白用户为等级%s结束  ------------------- ' % levelName)

    def saveALLMemebersInfoToXls(self, saveName):
        """
        取得会员信息表
        :param saveName:
        """
        currentPage = 1
        wb, sheet = loadXlsGetSheel(saveName, '会员信息')
        # 写入标题内容
        titleArray = ['序列', 'id', '用户名', '等级', '手机号', '车牌号', '加油次数', '余额', '剩余积分', '最后加油日期', '优惠券(张)', '推荐人数']
        i = 0
        for s in titleArray:
            sheet.cell(row=1, column=i + 1, value=s)
            i += 1

        row = 2
        pageSize = 30
        while True:
            url = 'https://api.aiyouzhan.cn/api/member/enterprise/userPageList?page=%s&size=30&token=%s' % (
                currentPage, self.token)
            json1 = self.getJsonByUrlWithGet(url)
            if json1['code'] == 1:
                totalRows, totalPage = self.getTotalRowsAndTotalPageByJson(json1, pageSize)

                # print('当前是 第%s页/共%s页 共%s条 完成:%s' % (currentPage,totalPage,totalRows,currentPage/totalPage))
                for json2 in json1['data']['rows']:
                    sheet.cell(row=row, column=1, value=row - 1)
                    sheet.cell(row=row, column=2, value='id-' + str(json2['id']))
                    sheet.cell(row=row, column=3, value=json2['username'])
                    sheet.cell(row=row, column=4, value=json2['levelName'])
                    sheet.cell(row=row, column=5, value=json2['phone'])
                    sheet.cell(row=row, column=6, value=json2['carLicenseNo'])
                    sheet.cell(row=row, column=7, value=json2['orderQty'])
                    sheet.cell(row=row, column=8, value=json2['balance'])
                    sheet.cell(row=row, column=9, value=json2['point'])
                    sheet.cell(row=row, column=10, value=json2['lastOrderTime'])
                    sheet.cell(row=row, column=11, value=json2['couponQty'])
                    sheet.cell(row=row, column=12, value=json2['refereeQty'])
                    row += 1

                self.view_bar('数据采集 ', currentPage, totalPage)
                currentPage += 1
                if currentPage > totalPage:
                    break;

            else:
                break;

        wb.save(saveName)
        print("\n处理完成....")

    def saveALLMemebersInfoToXls_thread(self, saveName):
        """
        取得会员信息表
        :param saveName:
        """
        baseUrl = 'https://api.aiyouzhan.cn/api/member/enterprise/userPageList?token=%s' % (self.token)
        pageSize = 30
        rows = self.getRowsFromUrl(baseUrl, pageSize)
        currentPage = 1
        wb, sheet = loadXlsGetSheel(saveName, '会员信息')
        # 写入标题内容
        titleArray = ['序列', 'id', '用户名', '等级', '手机号', '车牌号', '加油次数', '余额', '剩余积分', '最后加油日期', '优惠券(张)', '推荐人数']
        i = 0
        for s in titleArray:
            sheet.cell(row=1, column=i + 1, value=s)
            i += 1

        row = 2
        for json2 in rows:
            sheet.cell(row=row, column=1, value=row - 1)
            sheet.cell(row=row, column=2, value='id-' + str(json2['id']))
            sheet.cell(row=row, column=3, value=json2['username'])
            sheet.cell(row=row, column=4, value=json2['levelName'])
            sheet.cell(row=row, column=5, value=json2['phone'])
            sheet.cell(row=row, column=6, value=json2['carLicenseNo'])
            sheet.cell(row=row, column=7, value=json2['orderQty'])
            sheet.cell(row=row, column=8, value=json2['balance'])
            sheet.cell(row=row, column=9, value=json2['point'])
            sheet.cell(row=row, column=10, value=json2['lastOrderTime'])
            sheet.cell(row=row, column=11, value=json2['couponQty'])
            sheet.cell(row=row, column=12, value=json2['refereeQty'])
            row += 1

        wb.save(saveName)
        print("\n处理完成....")

    def saveALLMemebersBaseInfoToXls_thread(self, saveFileName):
        """
        取得会员信息表
        :param saveName:
        """
        baseUrl = 'https://%s/api/member/enterprise/getUserLevelReport?token=%s' % (self.host,self.token)
        pageSize = 50
        list = self.getRowsFromUrl(baseUrl, pageSize)

        titles = {
            "id": "编号",
            "userId": "用户编号",
            "username": "用户名",
            "phone": "联系电话",
            "carLicenseNo": "车牌",
            "totalCost": "总消费金额",
            "lastMonthCost": "上月消费金额",
            "thisMonthCost": "本月消费金额",
            "adjustLevelId": "建议会员等级编号",
            "adjustLevelName": "建议会员等级",
            "levelId": "当前等级编号",
            "levelName": "当前等级",
            "remark": "备注",
        }
        sheelName = "会员等级"
        self.saveListToXls(saveFileName, titles, list, sheelName)

        print("\n处理完成....")

    def updateUserLevelSetHasPhoneDefaultLevel(self, defaultLeveId, defaultLeveName, hasTelLeveId, pageSize=30,
                                               threadNum=10):
        """
        设置用有已经绑定电话号码的客户指定那个等级
        :param defaultLeveId:
        :param defaultLeveName:
        :param hasTelLeveId:  目标等级名称
        :param pageSize:
        :param threadNum:
        """
        currentPage = 1
        token = self.token
        url = 'https://api.aiyouzhan.cn/api/member/enterprise/getUserLevelReport?page=%s&size=%s&token=%s&t=%s' % (
            currentPage, pageSize, token, int(time.time()))

        totalPage = self.getTotalPage(url, pageSize)

        while True:
            threads = []
            for i in range(threadNum):
                t = threading.Thread(target=self.updateUserLevelSetDefaultLevelByCurrnetPage,
                                     args=(currentPage, pageSize, token, defaultLeveId, defaultLeveName, hasTelLeveId))
                t.start()

                threads.append(t)
                currentPage += 1
                if currentPage > totalPage:
                    break;

            # 等待所有线程完成
            for t in threads:
                t.join()

            self.view_bar('修改等级 ', currentPage, totalPage)

            if currentPage > totalPage:
                break;

        print("\n处理完成....")

    def updateUserLevelSetDefaultLevel2(self, defautLeveId, defaultLevelName, hasTelLeveId):
        currentPage = 1
        size = 30
        row = 1
        token = self.token
        while True:
            url = 'https://api.aiyouzhan.cn/api/member/enterprise/getUserLevelReport?page=%s&size=%s&token=%s&t=%s' % (
                currentPage, size, token, int(time.time()))
            rep = self.get(url, headers=self.header)
            rep.encoding = 'utf-8'

            json1 = rep.json()
            if json1['code'] == 1:
                totalRows = int(json1['data']['total'])
                totalPage = self.getTotolPage(totalRows, 30)

                # print('当前是 第%s页/共%s页 共%s条 完成:%s' % (currentPage,totalPage,totalRows,currentPage/totalPage))
                for json2 in json1['data']['rows']:
                    # 如果没有电话号码，没有等级 就设置为默认等级
                    if (json2['phone'] is None) and (json2['levelName'] is None):
                        # self.updateUserLevel(str(json2['userId']),defautLeveId,self.token);
                        threading.Thread(target=self.updateUserLevel,
                                         args=(str(json2['userId']), defautLeveId, self.token)).start()

                    # 如果有电话号码，并且是默认等级  就设置为有电话的等级
                    if (json2['phone'] is not None) and (json2['levelName'] == defaultLevelName):
                        # self.updateUserLevel(str(json2['userId']), hasTelLeveId, self.token);
                        threading.Thread(target=self.updateUserLevel,
                                         args=(str(json2['userId']), hasTelLeveId, self.token)).start()

                    # 如果有电话号码，并且是等级为空  就设置为有电话的等级
                    if (json2['phone'] is not None) and (json2['levelName'] is None):
                        # self.updateUserLevel(str(json2['userId']), hasTelLeveId, self.token);
                        threading.Thread(target=self.updateUserLevel,
                                         args=(str(json2['userId']), hasTelLeveId, self.token)).start()

                    row += 1

                self.view_bar('修改会员等级 ', currentPage, totalPage)
                currentPage += 1
                if currentPage > totalPage:
                    break;

            else:
                break;

        print("\n处理完成....")

    def updateUserLevelSetDefaultLevel(self, defautLeveId, defaultLevelName, hasTelLeveId):
        """

        :param defautLeveId:
        :param defaultLevelName:
        :param hasTelLeveId:
        """
        currentPage = 1
        size = 30
        row = 1
        token = self.token
        while True:
            url = 'https://api.aiyouzhan.cn/api/member/enterprise/getUserLevelReport?page=%s&size=%s&token=%s&t=%s' % (
                currentPage, size, token, int(time.time()))
            rep = self.get(url, headers=self.header)
            rep.encoding = 'utf-8'

            json1 = rep.json()
            if json1['code'] == 1:
                totalRows = int(json1['data']['total'])
                totalPage = self.getTotolPage(totalRows, 30)

                # print('当前是 第%s页/共%s页 共%s条 完成:%s' % (currentPage,totalPage,totalRows,currentPage/totalPage))
                for json2 in json1['data']['rows']:
                    # 如果没有电话号码，没有等级 就设置为默认等级
                    if (json2['phone'] is None) and (json2['levelName'] is None):
                        # self.updateUserLevel(str(json2['userId']),defautLeveId,self.token);
                        threading.Thread(target=self.updateUserLevel,
                                         args=(str(json2['userId']), defautLeveId, self.token)).start()

                    # 如果有电话号码，并且是默认等级  就设置为有电话的等级
                    if (json2['phone'] is not None) and (json2['levelName'] == defaultLevelName):
                        # self.updateUserLevel(str(json2['userId']), hasTelLeveId, self.token);
                        threading.Thread(target=self.updateUserLevel,
                                         args=(str(json2['userId']), hasTelLeveId, self.token)).start()

                    # 如果有电话号码，并且是等级为空  就设置为有电话的等级
                    if (json2['phone'] is not None) and (json2['levelName'] is None):
                        # self.updateUserLevel(str(json2['userId']), hasTelLeveId, self.token);
                        threading.Thread(target=self.updateUserLevel,
                                         args=(str(json2['userId']), hasTelLeveId, self.token)).start()

                    row += 1

                self.view_bar('修改会员等级 ', currentPage, totalPage)
                currentPage += 1
                if currentPage > totalPage:
                    break;

            else:
                break;

        print("\n处理完成....")

    def updateUserLevelSetDefaultLevelByCurrnetPage(self, currentPage, size, token, defautLeveId, defaultLevelName,
                                                    hasTelLeveId):
        """

        :param currentPage:
        :param size:
        :param token:
        :param defautLeveId:
        :param defaultLevelName:
        :param hasTelLeveId:
        """
        url = 'https://api.aiyouzhan.cn/api/member/enterprise/getUserLevelReport?page=%s&size=%s&token=%s&t=%s' % (
            currentPage, size, token, int(time.time()))
        rep = self.get(url, headers=self.header)
        rep.encoding = 'utf-8'

        json1 = rep.json()
        if json1['code'] == 1:
            # print('当前是 第%s页/共%s页 共%s条 完成:%s' % (currentPage,totalPage,totalRows,currentPage/totalPage))
            for json2 in json1['data']['rows']:
                # 如果没有电话号码，没有等级 就设置为默认等级
                if (json2['phone'] is None) and (json2['levelName'] is None):
                    self.updateUserLevel(str(json2['userId']), defautLeveId, self.token);
                    # threading.Thread(target=self.updateUserLevel,args=( str(json2['userId']),defautLeveId,self.token )).start()

                # 如果有电话号码，并且是默认等级  就设置为有电话的等级
                if (json2['phone'] is not None) and (json2['levelName'] == defaultLevelName):
                    self.updateUserLevel(str(json2['userId']), hasTelLeveId, self.token);
                    # threading.Thread(target=self.updateUserLevel,args=(str(json2['userId']), hasTelLeveId, self.token)).start()

                # 如果有电话号码，并且是等级为空  就设置为有电话的等级
                if (json2['phone'] is not None) and (json2['levelName'] is None):
                    self.updateUserLevel(str(json2['userId']), hasTelLeveId, self.token);
                    # threading.Thread(target=self.updateUserLevel,args=(str(json2['userId']), hasTelLeveId, self.token)).start()

    def getUserPageList(self, token, saveName):
        currentPage = 1
        wb, sheet = loadXlsGetSheel(saveName, '会员信息')
        # 写入标题内容
        titleArray = ['序列', 'id', '用户名', '等级', '手机号', '车牌号', '加油次数', '余额', '剩余积分', '最后加油日期', '优惠券(张)', '推荐人数']
        i = 0
        for s in titleArray:
            sheet.cell(row=1, column=i + 1, value=s)
            i += 1

        row = 2
        pageSize = 30
        while True:
            url = 'https://api.aiyouzhan.cn/api/member/enterprise/userPageList?page=%s&size=30&token=%s' % (
                currentPage, token)
            rep = self.get(url, headers=self.header)

            rep.encoding = 'utf-8'
            json1 = rep.json()
            if json1['code'] == 1:
                totalRows = int(json1['data']['total'])
                totalPage = int(totalRows / pageSize) if totalRows % pageSize < 1 else int(totalRows / pageSize) + 1

                # print('当前是 第%s页/共%s页 共%s条 完成:%s' % (currentPage,totalPage,totalRows,currentPage/totalPage))
                for json2 in json1['data']['rows']:
                    sheet.cell(row=row, column=1, value=row - 1)
                    sheet.cell(row=row, column=2, value='id-' + str(json2['id']))
                    sheet.cell(row=row, column=3, value=json2['username'])
                    sheet.cell(row=row, column=4, value=json2['levelName'])
                    sheet.cell(row=row, column=5, value=json2['phone'])
                    sheet.cell(row=row, column=6, value=json2['carLicenseNo'])
                    sheet.cell(row=row, column=7, value=json2['orderQty'])
                    sheet.cell(row=row, column=8, value=json2['balance'])
                    sheet.cell(row=row, column=9, value=json2['point'])
                    sheet.cell(row=row, column=10, value=json2['lastOrderTime'])
                    sheet.cell(row=row, column=11, value=json2['couponQty'])
                    sheet.cell(row=row, column=12, value=json2['refereeQty'])
                    row += 1

                self.view_bar('数据采集 ', currentPage, totalPage)
                currentPage += 1
                if currentPage > totalPage:
                    break;

            else:
                break;

        wb.save(saveName)
        print("\n处理完成....")

    def getWechatInfoByUserId(self, userId):
        """
        #通过用户ID号获取用户微信信息
        :param userId:
        :return:{"id":"1208195634151059458","enterpriseId":"1206405094485028865","realName":null,"birthday":null,"username":"事与愿违","headImgUrl":"http://thirdwx.qlogo.cn/mmopen/I1OPdTuWhE9icVeO1w4LlBmicyQBua5usic6wB0AZ4jNz3xqTI5eYs2BzAaNYIyK65ECrlz2LPmToTiaDH5rcVK0coSF1TlonI9K/132","sex":2,"phone":null,"idCard":null,"carLicenseNo":null,"country":"中国","province":"四川","city":"内江","refereeId":null,"refereeOperatorId":null,"balance":null,"point":null,"forcedUpdateTime":"2020-01-31 12:48:27"}
        """
        url = "https://api.aiyouzhan.cn/api/member/enterprise/getUserById?id=%s&token=%s&t=%s" % (
            userId, self.token, int(time.time()))
        json1 = self.getJsonByUrlWithGet(url)
        if json1 is None or json1['data'] is None:
            return None
        return json1['data']

    def getOilTypeIdByName(self, oilTypeName):
        # https://api.aiyouzhan.cn/api/gas/enterprise/getOilTypes?t=1573812732093&token=1195276185488089088
        url = "https://api.aiyouzhan.cn/api/gas/enterprise/getOilTypes?t=%s&token=%s" % (int(time.time()), self.token)
        json1 = self.getJsonByUrlWithGet(url)
        if json1 is None:
            return None
        rows = json1['data']['rows']
        for row in rows:
            if row['name'] == oilTypeName:
                return row['id']
        return None

    def getLevelRuleIdByName(self, name):
        """
        通过等级名称转等级相对应的ID号
        :param name: 等级名称
        :return: 等级的ID
        """

        if name is None or type(name) != str:
            return None

        # https://api.aiyouzhan.cn/api/member/enterprise/getLevelRules?t=%s&token=%s
        url = "https://api.aiyouzhan.cn/api/member/enterprise/getLevelRules?t=%s&token=%s" % (
            int(time.time()), self.token)
        json1 = self.getJsonByUrlWithGet(url)
        if json1 is None:
            return None
        rows = json1['data']['rows']
        for row in rows:
            if row['name'] == name:
                return row['id']
        return None

    def getLevelRulesInfo(self):
        """
        取得当前油站的所有的等级信息
        :return:
        """
        baseUrl = "https://api.aiyouzhan.cn/api/member/enterprise/getLevelRules?token=%s" % (self.token)
        print(baseUrl)
        list = self.getRowsFromUrl(baseUrl)
        return list

    # 取得时间之后的充值会员信息
    def get_Recharge_Users_After_time(self, afterTime, pageSize=10):

        url = "https://api.aiyouzhan.cn/api/member/enterprise/getRechargeOrderList?page=%s&size=%s&token=%s&t=%s" % (
            1, pageSize, self.token, int(time.time()))
        totalPage = self.getTotalPagesFromUrl(url, pageSize)
        page = totalPage
        list = []
        while True:
            url = "https://api.aiyouzhan.cn/api/member/enterprise/getRechargeOrderList?page=%s&size=%s&token=%s&t=%s" % (
                page, pageSize, self.token, int(time.time()))
            json1 = self.getJsonByUrlWithGet(url, )
            if json1["code"] == 1 and json1['data'] is not None and json1['data']['rows'] is not None:
                rows = json1['data']['rows']

                rechargeTime = getDateTimeFromString(rows[-1]['rechargeTime'])
                # 如果当前充值时间超过或等于最后退出
                if afterTime >= rechargeTime: break

                list.extend(rows)

            if page < 1:  break
            page = page - 1
        list.reverse()
        return list

    def printLevelRulesInfo(self):
        """
            打印会员等级信息
        """
        list = self.getLevelRulesInfo()
        print("-------------- 打印会员等级信息 --------------")
        for o in list:
            print("%s. 等级名称：%s" % (list.index(o) + 1, o['name']))

    # 取得油站所有加油员工信息
    # 返回模式JSON
    def getAllOilEmployees(self):
        pageSize = 20
        page = 1

        arr = []
        while True:
            url = "https://api.aiyouzhan.cn/api/enterprise/enterprise/operator-user/page-list?page=%s&size=%s&token=%s&t=%s" % (
                page, pageSize, self.token, int(time.time()))
            # print(url)
            # print(self.token)
            json1 = self.getJsonByUrlWithGet(url)

            # 如果访问出错就退出
            if json1 is None or json1['code'] != 1:
                print('访问出错就退出')
                break;

            arr += json1['data']['rows']
            page += 1
            totalPages = self.getTotalPageByJson(json1, pageSize)
            if page > totalPages:
                break;

        # 返回为空
        return arr

    # 添加成黑名单
    # param userId用户编号
    def addBlackUser(self, userId):
        postUrl = "https://api.aiyouzhan.cn/api/member/enterprise/addBlackUser?t=%s" % (int(time.time()))
        data = url_encode({
            'userId': userId,
            'identity': 1,
            'token': self.token,
        })
        json1 = self.getJsonByUrlWithPost(postUrl, data)
        print(json1)
        if json1 is not None and json1['code'] == 1:
            return True
        return False

    # 取得用户所有未使用的优惠券
    def getUserAllUnuseCoupon(self, userId):
        url = "https://api.aiyouzhan.cn/api/coupon/enterprise/coupon/page-list-android?status=%s&userId=%s&token=%s" % (
            1, userId, self.token)
        return self.getRowsFromUrl(url)

    # 取得用户所有禁用的优惠券
    def getUserAllDisableCoupon(self, userId):
        url = "https://api.aiyouzhan.cn/api/coupon/enterprise/coupon/page-list-android?status=%s&userId=%s&token=%s" % (
            0, userId, self.token)
        return self.getRowsFromUrl(url)

    # 禁用优惠券
    def disableCoupon(self, couponId):
        postUrl = 'https://api.aiyouzhan.cn/api/coupon/enterprise/coupon/disable?t=%s' % (int(time.time()))
        data = url_encode({
            'id': couponId,
            'token': self.token,
        })
        json1 = self.getJsonByUrlWithPost(postUrl, data)
        print(json1)
        if json1 is not None and json1['code'] == 1:
            return True
        return False

    # 禁用优惠券
    def enableCoupon(self, couponId):
        postUrl = 'https://api.aiyouzhan.cn/api/coupon/enterprise/coupon/enable?t=%s' % (int(time.time()))
        data = url_encode({
            'id': couponId,
            'token': self.token,
        })
        json1 = self.getJsonByUrlWithPost(postUrl, data)
        print(json1)
        if json1 is not None and json1['code'] == 1:
            return True
        return False

    # 启用所有用户禁用所有优惠券
    def enableUserAllDisableCoupons(self, userId):
        rows = self.getUserAllDisableCoupon(userId)
        for row in rows:
            print('启用第', rows.index(row) + 1, '张优惠券')
            self.enableCoupon(row['id'])

        print(rows)

    # 禁用用户所有优惠券
    def disableUserAllCoupons(self, userId):
        rows = self.getUserAllUnuseCoupon(userId)
        for row in rows:
            print('禁用第', rows.index(row) + 1, '张优惠券')
            self.disableCoupon(row['id'])

    # 禁用所有加油员的优惠券
    def disableAllOilEmployeesAllCoupons(self):
        employees = self.getAllOilEmployees()
        for e in employees:
            # 未绑定微信不处理
            if e['memberUserId'] is None:
                continue
            userId = e['memberUserId']
            # 禁用用户所有优惠券
            print("开始禁用加油员：%s 所有优惠券" % (e["name"]))
            self.disableUserAllCoupons(userId)

    # 取得用户所有禁用的优惠券数量
    def getTotalNumUserAllDisableCoupon(self, userId):
        url = "https://api.aiyouzhan.cn/api/coupon/enterprise/coupon/page-list-android?status=%s&userId=%s&token=%s" % (
            0, userId, self.token)
        return self.getTotolRowsFromUrl(url)

    # 取得用户所有的优惠券数量
    def getTotalNumUserAllUnuseCoupon(self, userId):
        url = "https://api.aiyouzhan.cn/api/coupon/enterprise/coupon/page-list-android?status=%s&userId=%s&token=%s" % (
            1, userId, self.token)
        return self.getTotolRowsFromUrl(url)

    # 取得加油目前所有加油员禁用的优惠券数量
    def getTotalAllOilEmployeesDisableCoupons(self):
        employees = self.getAllOilEmployees()
        total = 0
        for e in employees:
            # 未绑定微信不处理
            if e['memberUserId'] is None:
                continue
            userId = e['memberUserId']

            temp = self.getTotalNumUserAllDisableCoupon(userId)
            print("加油员：%s 禁用优惠券：%s" % (e["name"], temp))

            total += temp
        print("加油站共%s张优惠券" % (total))
        return total

    # 取得加油目前所有加油员禁用的优惠券数量
    def getTotalAllOilEmployeesUnuseCoupons(self):
        employees = self.getAllOilEmployees()
        total = 0
        employeesCoupons = []
        for e in employees:
            # 未绑定微信不处理
            if e['memberUserId'] is None:
                continue
            userId = e['memberUserId']

            temp = self.getTotalNumUserAllUnuseCoupon(userId)
            print("加油员：%s 优惠券：%s" % (e["name"], temp))
            employeesCoupons.append("加油员：%s 优惠券：%s" % (e["name"], temp))
            total += temp
        print("加油站共%s张优惠券" % (total))
        return total, employeesCoupons

    # 取得油站企业信息
    # "data": { "id": "XXX", "name": "XXX", "type": 2, "legalPerson": "XXX", "licenseNo": null, "organizationNo": null, "contact": "XXX", "phone": "XXX", "address": "XXX", "logoUrl": "", "status": 3, "csUserName": "XXX", "bmUserName": "XXX", "enterpriseCode": null, "yktEnterpriseSn": null}
    def getEnterpriseInfo(self):
        url = "https://api.aiyouzhan.cn/api/enterprise/enterprise/enterprise/get?t=%s&token=%s" % (
            int(time.time()), self.token)
        json1 = self.getJsonByUrlWithGet(url)
        if json1 is None or json1['data'] is None:
            return None
        return json1['data']

    # 把所有的加油员放入黑名单
    def addAllOilEmployeesToBlankUser(self):
        employees = self.getAllOilEmployees()
        for e in employees:
            # 未绑定微信不处理
            if e['memberUserId'] is None:
                continue
            print("把%s名员工放入黑名单" % (employees.index(e) + 1))
            self.addBlackUser(e['memberUserId'])

    # 禁用所有加油员的优惠券并放入黑名单
    def disableAllOilEmployeesAllCouponsAndAddAllOilEmployeesToBlankUser(self):
        # 禁用所有加油员的优惠券
        self.disableAllOilEmployeesAllCoupons()
        # 放入黑名单
        self.addAllOilEmployeesToBlankUser()

    # 打印出所有加油员的对应的微信信息
    # {"id": "XXXXX", "memberUserId": "XXXXX", "enterpriseId": "XXXXX", "gasStationId": "XXXXX", "gasStationName": "", "username": "SR", "name": "森磊", "phone": "18850329384", "code": "AI00886", "status": 1, "roles": [{"id": "1067311084165251073", "code": "user", "name": "加油员", "description": "加油员", "status": 1, "resources": [{"id": "1", "code": "oper:gas:order:create", "name": "创建加油订单", "status": 1}
    def printAllEmployessWechatInfo(self):
        info = self.getEnterpriseInfo()
        print("------------- %s  -------------" % (info['name']))
        employees = self.getAllOilEmployees()
        for e in employees:
            # 未绑定微信不处理
            if e['memberUserId'] is None:
                continue
            wechatInfo = self.getWechatInfoByUserId(e['memberUserId'])
            # print(wechatInfo)
            userName = ""
            if wechatInfo is not None:
                userName = wechatInfo['username']
            print("%s . 加油员名称:%s  电话：%s  对应微信名：%s" % (employees.index(e) + 1, e['name'], e['phone'], userName))

    # 打印交接班客户充值余额 充值期未数
    def print_the_customer_recharge_balance_of_shift_handover(self, startTime, endTime, starting_balance, saveFileName):
        list = self.getListShift(startTime, endTime)
        print("共%s条交接班数据" % len(list))
        detailList = []
        i=0
        size=len(list)
        for o in list:
            # print(o)
            shiftId = o["id"]
            i+=1
            print("查看%s数据  %s/%s" % (shiftId,i,size))
            detail = self.getDetailsShift(shiftId)
            detailList.append(detail)

        wb1, sheet = loadXlsGetSheel(saveFileName, '汇总')
        titels = {"id": "编号",
                  "startTime": "开始时间",
                  "endTime": "结束时间",
                  "rehcargeGiftAmount": "线上赠送（元）",
                  "rechargeAmount": "线上收款（元）",
                  "addBalance": "手工增加（元）",
                  "moveBalance": "手工减少（元）",
                  "balanceAmount": "余额支付（元）",
                  "totalFleetAmount":"车队支付"
                  }
        row = 1
        column = 1
        print("生成表头...")
        for key in titels.keys():
            sheet.cell(row=row, column=column, value=titels[key])
            column += 1
        sheet.cell(row=row, column=column, value="未消费金额")

        row += 1
        not_consumed_amount = starting_balance
        detailList.reverse()
        print("生成数据.....")
        for item in detailList:
            column = 1
            print("生成第%s行数据...." % row)
            for key in titels.keys():
                sheet.cell(row=row, column=column, value=item[key])
                column += 1
            not_consumed_amount = not_consumed_amount + float(item["rehcargeGiftAmount"]) + float(item["rechargeAmount"]) + float(
                item["addBalance"]) - float(item["moveBalance"]) - float(item["balanceAmount"])- float(item["totalFleetAmount"])
            sheet.cell(row=row, column=column, value=not_consumed_amount)
            row += 1

        wb1.save(saveFileName)
        print("OK")

    # 取得加油站的营销活动
    # name活动标题 type 活动类型 isGoing为1时表时进行中
    # type = 1新关注 2成功推广用户; 3手工发券; 4微信分享; 5加油返券; 6扫码送券; 7推广会员激活; 8充值领券; 9加油推广送券;
    # 返回json={ "id": "1215521487461572609", "enterpriseId": "1082614775604600833", "stationId": "1082631939535429633", "name": "线上消费返100元代金券", "type": 5, "oilTypeIds": "1084695278352625666,1084695327199490050", "startTime": "2020-01-15 00:00:00", "endTime": "2020-01-31 23:59:59", "description": "线上消费返100元代金券，20元*5张，满200元使用一张", "needMember": "0", "allowPayMethods": "微信,支付宝,现金,POS", "delayDay": 0, "activeDay": 90, "couponStartTime": null, "couponEndTime": null, "limitTimes": "", "limitWeeks": "四", "limitDays": null, "mutualUse": "0", "maxPerUser": null, "maxPerDay": null, "status": 1, "createTime": "2020-01-10 14:31:21", "stationName": "中国国际能源(胜天站)", "quantity": 5, "memberLevel": "", "amountType": 1, "minAmount": 1.0, "maxAmount": 100000.0, "minArriveAmount": null, "maxArriveAmount": null, "giveOilType": "1084695278352625666,1084695327199490050", "limitJoinTimes": null, "limitDaysJoinTimes": null, "limitWeeksJoinTimes": null, "limitMonthJoinTimes": null, "remainJoinTimes": null, "remainDaysJoinTimes": null, "remainWeeksJoinTimes": null, "remainMonthJoinTimes": null}
    def getIsGoingActivity(self, name='', type=''):
        isGoing = 1
        list = self.getActivity(name=name, type=type, isGoing=isGoing)
        return list

    # 取得加油站的营销活动
    # 取得加油站的营销活动
    # name活动标题 type 活动类型 isGoing为1时表时进行中
    # type = 1新关注 2成功推广用户; 3手工发券; 4微信分享; 5加油返券; 6扫码送券; 7推广会员激活; 8充值领券; 9加油推广送券;
    # 返回json={ "id": "1215521487461572609", "enterpriseId": "1082614775604600833", "stationId": "1082631939535429633", "name": "线上消费返100元代金券", "type": 5, "oilTypeIds": "1084695278352625666,1084695327199490050", "startTime": "2020-01-15 00:00:00", "endTime": "2020-01-31 23:59:59", "description": "线上消费返100元代金券，20元*5张，满200元使用一张", "needMember": "0", "allowPayMethods": "微信,支付宝,现金,POS", "delayDay": 0, "activeDay": 90, "couponStartTime": null, "couponEndTime": null, "limitTimes": "", "limitWeeks": "四", "limitDays": null, "mutualUse": "0", "maxPerUser": null, "maxPerDay": null, "status": 1, "createTime": "2020-01-10 14:31:21", "stationName": "中国国际能源(胜天站)", "quantity": 5, "memberLevel": "", "amountType": 1, "minAmount": 1.0, "maxAmount": 100000.0, "minArriveAmount": null, "maxArriveAmount": null, "giveOilType": "1084695278352625666,1084695327199490050", "limitJoinTimes": null, "limitDaysJoinTimes": null, "limitWeeksJoinTimes": null, "limitMonthJoinTimes": null, "remainJoinTimes": null, "remainDaysJoinTimes": null, "remainWeeksJoinTimes": null, "remainMonthJoinTimes": null}
    def getCouponActivity(self, name='', type='', isGoing=''):
        baseUrl = "https://api.aiyouzhan.cn/api/coupon/enterprise/activity/page-list?&name=%s&type=%s&isGoing=%s&token=%s" % (
            name, type, isGoing, self.token)
        return self.getRowsFromUrl(baseUrl)

    # 添加活动
    def create_activity_by_payload(self, payload):
        url = "https://api.aiyouzhan.cn/api/coupon/enterprise/activity/create?token=%s&t=%s" % (
            self.token, int(time.time()))
        payload = json.dumps(payload)
        headers = {
            'Connection': "keep-alive",
            'Accept': "application/json, text/javascript, */*; q=0.01",
            'Origin': "https://%s" % self.host,
            'Content-Type': "application/json",
            'Sec-Fetch-Site': "same-site",
            'Sec-Fetch-Mode': "cors",
            'Referer': "https://%s/index.html" % self.host,
            'Accept-Encoding': "gzip, deflate, br",
            'Accept-Language': "zh-CN,zh;q=0.9",
            'cache-control': "no-cache",
        }
        self.header.update(headers)

        rep = self.post(url=url, data=payload, headers=self.header)
        print(rep.text)
        if rep.text.__contains__('"code":1'):
            return rep.json()["data"]
        return None

    def add_coupon_to_activity_by_payload(self, payload):
        url = "https://api.aiyouzhan.cn/api/coupon/enterprise/activityTemplate/create?token=%s&t=%s" % (
            self.token, int(time.time()))
        payload = json.dumps(payload)
        headers = {
            'Connection': "keep-alive",
            'Accept': "application/json, text/javascript, */*; q=0.01",
            'Origin': "https://%s" % self.host,
            'Content-Type': "application/json",
            'Sec-Fetch-Site': "same-site",
            'Sec-Fetch-Mode': "cors",
            'Referer': "https://%s/index.html" % self.host,
            'Accept-Encoding': "gzip, deflate, br",
            'Accept-Language': "zh-CN,zh;q=0.9",
            'cache-control': "no-cache",
        }
        self.header.update(headers)

        rep = self.post(url=url, data=payload, headers=self.header)
        print(rep.text)
        return rep.text

    def add_coupon_to_activity(self, activityId="", couponName="", couponType=0, couponCost="", description="",
                               quantity=1, allowGiveAway="", maxActivePerUser=""):
        if activityId.__eq__(""): return
        couponId = self.get__coupon_template_id(couponName, couponType)
        if couponId is None:
            print("没有找到优惠券")
        else:
            payload = {"id": "", "templateId": couponId, "couponCost": couponCost, "description": description,
                       "quantity": quantity, "allowGiveAway": allowGiveAway, "maxActivePerUser": maxActivePerUser,
                       "activityId": activityId, "token": self.token}
            self.create_coupon_activity_by_payload(payload)

    # 打印当前正在进行的活动
    def printIsGoingCouponActivity(self, name='', type=''):
        self.printCouponActivity(name=name, type=type, isGoing=1)


    def printCouponActivity(self, name='', type='', isGoing=''):
        rows = self.getCouponActivity(name=name, type=type, isGoing=isGoing)
        outStr ="-------------- 打印优惠券活动(%s) --------------\n" % (len(rows))

        for o in rows:
            print("========== %s =============" % (rows.index(o) + 1))
            endTime = getDateTimeFromString(o["endTime"])
            print(o["endTime"], "-----------", endTime)
            if endTime is None:
                endTime = datetime.datetime.now()
            delta = getDeltaDaysWithNow(endTime)
            outStr += "%s. %s 类型:%s 名称：%s 日期：%s~%s  有效期：%s \n" % (
                rows.index(o) + 1, o["id"], self.activityTypes[o["type"] - 1], o["name"], o["startTime"], o["endTime"],
                delta)

            outStr += self.print_activity_coupon_list(o["id"])
            outStr += "\n"

        print(outStr)
        return outStr

    def print_activity_coupon_list(self, activityId):
        """
            打印活动下的优惠券
        :param activityId:
        """

        baseUrl = "https://api.aiyouzhan.cn/api/coupon/enterprise/activityTemplate/list?activityId=%s&token=%s" % (
            activityId, self.token)

        rows = self.getRowsFromUrlByNoThread(baseUrl)
        if len(rows)<0: return "无优惠券\n"
        res="优惠券（%s种）\n" %(len(rows))
        for o in rows:
            res+=" 优惠券名称:%s 类型:%s 面值:%s 用券金额限制:%s 是否允许赠送:%s 赠送数量: %s 用户最多优惠券:%s 备注：%s \n" % (
                o["couponName"], o["type"], o["amount"], o["couponCost"], o["allowGiveAway"], o["quantity"],
                o["maxActivePerUser"], o["description"])

        return res

    # 取得加油站的立减活动
    # timeStatus 0 正在进行中；1未开始；2已经过期
    # status 1启用;0禁用
    # 返回JSON ={ "id": "1213295926626508801", "name": "汽油加满210元减50元", "startTime": "2020-01-04 00:00:00", "endTime": "2020-01-15 23:59:59", "activityType": 1, "deductType": 1, "memberLevel": "", "oilTypeIds": "1208225450787102721,1208225607612129282", "allowPayMethods": "微信,支付宝,现金,POS", "description": "汽油加满210元减50元", "status": 0}
    def getDeductActivity(self, status=1, timeStatus=0):
        baseUrl = "https://api.aiyouzhan.cn/api/gas/enterprise/deduct/deductList?status=%s&timeStatus=%s&token=%s" % (
            status, timeStatus, self.token)
        list = self.getRowsFromUrl(baseUrl)
        return list

    def printDeductActivity(self, status=1, timeStatus=0):
        """
        #取得加油站的立减活动
        :param status: 1启用;0禁用
        :param timeStatus:  0 正在进行中；1未开始；2已经过期
        """
        list = self.getDeductActivity(status=status, timeStatus=timeStatus);
        print("-------------- 打印立减活动 --------------")
        for o in list:
            endTime = getDateTimeFromString(o["endTime"])
            if endTime is None:
                endTime = datetime.datetime.now()
            delta = getDeltaDaysWithNow(endTime)
            print("%s.  名称：%s 日期：%s~%s 有效期：%s" % (list.index(o) + 1, o["name"], o["startTime"], o["endTime"], delta))

    def analyze_order_plate_ratio_period(self, aday=datetime.datetime.now(),period_day=3, but_oilTypeNames=[], keep_the_license_plate=[],
                                  min_amount=50):

        for i in range(period_day):
            aday = aday+datetime.timedelta(days=-1*i)
            df =self.analyze_order_plate_ratio(aday=aday,but_oilTypeNames=but_oilTypeNames,keep_the_license_plate=keep_the_license_plate,min_amount=min_amount)
            for index, row in df.iterrows():
                title=row[0]
                count = row[1]
                print(index, row[0], row[1], )
        pass

    def analyze_order_plate_ratio(self,aday=datetime.datetime.now(),but_oilTypeNames=[],keep_the_license_plate=[],min_amount=50):
        """

        :param aday:某一天数据
        :param but_oilTypeNames: 不统计那种油品
        :param keep_the_license_plate:那些车牌保留，其它车牌归成其它
        :param min_amount 最小订单金额
        :return:
        """

        startDate = '%s 0:00:00' % aday.strftime('%Y-%m-%d')
        endDate = '%s 23:59:59' %  aday.strftime('%Y-%m-%d')
        print(endDate)

        list2 = self.searchOrder(status=2,startDate=startDate,endDate=endDate)
        list=[]
        if len(but_oilTypeNames)>0:
            for o1 in list2:
                        #删除不显示的油品或低于某个金额的订单
                if o1["oilTypeName"]  in but_oilTypeNames or int(o1['amount'])<min_amount:
                    print('del list 微信：%s 油品：%s 金额：%s' %(o1["wxName"],o1["oilTypeName"],o1['amount']))
                    continue
                else:
                    list.append(o1)
        print(len(list))
        if len(keep_the_license_plate)>0:
            for o in list:
                o['carLicenseNo']=str(o['carLicenseNo'])[0:2]
                if str(o['carLicenseNo']).__eq__(""):
                    o['carLicenseNo']='无车牌'
                elif str(o['carLicenseNo'])  not in keep_the_license_plate:
                    print(o['carLicenseNo'],'-----','其它车牌')
                    o['carLicenseNo']='其它车牌'

        df = pd.DataFrame(list)

        df['carLicenseNo'] = df['carLicenseNo'].str[0:2]
        df = pd.DataFrame(df['carLicenseNo'].items(),columns=["序号","车牌"])
        print("columns=",df.columns)


        df =  df.groupby(by="车牌")["车牌"].count()
        df = pd.DataFrame(df)
        df["占比"]=round(df["车牌"]/df["车牌"].sum(),2)
        return df



    # 取得加油站充值活动
    # 返回JSON ={ "id": "1215136295756521474", "type": 1, "rewardType": 2, "minRecharge": 1000.0, "maxRecharge": 4999.0, "percent": 6.0, "name": "汽油充值1000-4999元", "addAmount": null, "sorter": 1, "startTime": "2020-01-15", "endTime": "2020-01-31", "status": 1, "explain": "汽油充值1000-4999元返6%再赠送10％代金券"}
    def getRechargeActivity(self):
        baseUrl = "https://api.aiyouzhan.cn/api/member/enterprise/getRechargeSets?token=%s" % (self.token)
        return self.getRowsFromUrl(baseUrl)

    # 返回JSON ={ "id": "1215136295756521474", "type": 1, "rewardType": 2, "minRecharge": 1000.0, "maxRecharge": 4999.0, "percent": 6.0, "name": "汽油充值1000-4999元", "addAmount": null, "sorter": 1, "startTime": "2020-01-15", "endTime": "2020-01-31", "status": 1, "explain": "汽油充值1000-4999元返6%再赠送10％代金券"}
    def printRechargeActivity(self, status=None):
        list = self.getRechargeActivity();
        statusStr = ["禁用", "启用"]
        print("-------------- 打印充值活动 --------------")
        for o in list:
            if status is not None and o["status"] != status:
                continue

            now = datetime.datetime.now()
            endTime = getDateTimeFromString(o["endTime"])
            if endTime is None:
                endTime = now
            delta = getDeltaDaysWithNow(endTime)
            if delta < 1:
                continue
            print("%s.  名称：%s 日期：%s~%s 状态:%s 有效期：%s" % (
                list.index(o) + 1, o["name"], o["startTime"], o["endTime"], statusStr[o["status"]], delta))

    # 输入出当前所有加油站活动
    def printAllActivity(self):
        self.printIsGoingCouponActivity()
        self.printDeductActivity()
        self.printRechargeActivity(status=1)

    # 取得预警信息
    def getWarningInformation(self):

        pass

    def search_coupon_template(self, name, type):
        url = "https://api.aiyouzhan.cn/api/coupon/enterprise/template/page-list?name=%s&type=%s&token=%s&t=%s" % (
            name, type, self.token, int(time.time() * 1000))
        rows = self.getRowsFromUrl(url)
        return rows

    def is_eixts_coupon_template(self, name, type):
        if self.get__coupon_template_id(name, type) is None:
            return False
        return True

    def get__coupon_template_id(self, name, type):
        url = "https://api.aiyouzhan.cn/api/coupon/enterprise/template/page-list?name=%s&type=%s&token=%s" % (
            name, type, self.token)
        rows = self.getRowsFromUrlByNoThread(url)
        print(rows)
        for row in rows:
            if str(row["name"]).__eq__(name):
                return row["id"]
        return None

    # 活动内是否已经添加了这个类型的优惠券
    def is_activity_has_coupon_template_id(self, activityId, template_id):
        if activityId is None or template_id is None:
            return False
        url = "https://%s/api/coupon/enterprise/activityTemplate/list?activityId=%s&token=%s" % (self.host,
        activityId, self.token)
        list = self.getRowsFromUrlByNoThread(url)

        if list is None:
            return False
        for o in list:
            print(o["templateId"])
            if str(o["templateId"]).__eq__(template_id):
                return True
        return False

    def del_coupon_template_by_id(self, id):
        url = "https://%s/api/coupon/enterprise/template/delete?t=%s" % (self.host,int(time.time()))
        data = url_encode({
            'id': id,
            'token': self.token,
        })
        self.post(url, data, headers=self.header)

    # 定额券生成
    def create_coupon_template(self, name="", minReduce="", style="", type="", description="", minPercent="",
                               maxReduce=""):
        url = "https://api.aiyouzhan.cn/api/coupon/enterprise/template/create?token=%s&t=%s" % (
            self.token, int(time.time() * 1000))
        data = json.dumps(
            {"id": "", "style": style, "name": name, "type": type, "minReduce": minReduce, "description": description,
             "token": self.token})
        if type == 3:
            data = json.dumps(
                {"id": "", "style": style, "name": name, "type": type, "minPercent": minPercent, "maxReduce": maxReduce,
                 "description": description, "token": self.token})

        headers = {
            'Accept': "application/json, text/javascript, */*; q=0.01",
            'Origin': "https://%s" % self.host,
            'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
            'Content-Type': "application/json",
            'Sec-Fetch-Site': "same-site",
            'Sec-Fetch-Mode': "cors",
            'Referer': "https://%s/index.html" % self.host,
            'Accept-Encoding': "gzip, deflate, br",
            'Accept-Language': "zh-CN,zh;q=0.9",
            'cache-control': "no-cache",
        }
        self.header.update(headers)

        rep = self.post(url=url, data=data, headers=self.header)
        print(rep.text)

    def create_coupon_template_by_payload(self, payload):
        url = "https://api.aiyouzhan.cn/api/coupon/enterprise/template/create?token=%s&t=%s" % (
            self.token, int(time.time() * 1000))
        payload = json.dumps(payload)

        headers = {
            'Accept': "application/json, text/javascript, */*; q=0.01",
            'Origin': "https://%s" % self.host,
            'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
            'Content-Type': "application/json",
            'Sec-Fetch-Site': "same-site",
            'Sec-Fetch-Mode': "cors",
            'Referer': "https://%s/index.html" % self.host,
            'Accept-Encoding': "gzip, deflate, br",
            'Accept-Language': "zh-CN,zh;q=0.9",
            'cache-control': "no-cache",
        }
        self.header.update(headers)

        rep = self.post(url=url, data=payload, headers=self.header)
        print(rep.text)

    def create_coupon_activty(self):
        pass

    def createGasStationMonthReportToBoss(self):
        pass

    def createGasStationMonthReportToManager(self):
        pass

    def createGasStationMonthReportToServicer(self):
        pass

    def download_DataReport_Of_last_Month(self, saveFileName="download_DataReport_Of_last_Month.xls"):
        url = "https://api.aiyouzhan.cn/api/report/enterprise/monthReport/getMonthReportPage?token=%s&page=1&size=1&t=%s" % (
            self.token, int(time.time()))
        json1 = self.getJsonByUrlWithGet(url)
        if json1 is None or json1["data"] is None or json1["data"]["rows"] is None or json1["data"]["rows"][0] is None:
            return ""
        row = json1["data"]["rows"][0]
        url = "https://api.aiyouzhan.cn/api/report/enterprise/monthReport/downloadMonthReport?id=%s&token=%s" % (
            row["id"], self.token)
        print(url)
        r = requests.get(url)
        with open(saveFileName, "wb") as code:
            code.write(r.content)
        return saveFileName
    def print_all_user_counpon_info(self,beginTime=None,endTime=None, pageSize=50):
        if beginTime is None:
            now = datetime.datetime.now()
            beginTime = now+ datetime.timedelta(days=-1)
            print("beginTime = %s-%s-%s 00:00:00" % (beginTime.year, beginTime.month, beginTime.day))
            print("endTime = %s-%s-%s 23:59:59" %(beginTime.year,beginTime.month,beginTime.day))

            endTime = datetime.datetime.strptime("%s-%s-%s 23:59:59" %(beginTime.year,beginTime.month,beginTime.day), '%Y-%m-%d %H:%M:%S')
            beginTime = datetime.datetime.strptime("%s-%s-%s 00:00:00" %(beginTime.year,beginTime.month,beginTime.day), '%Y-%m-%d %H:%M:%S')
        else:
            beginTime = getDateTimeFromString(beginTime)
            endTime = getDateTimeFromString(endTime)


        url = "https://enterprise.aiyouzhan.cn/api/coupon/enterprise/coupon/page-list?token=%s&t=%s" % (
            self.token, int(time.time()))
        totalPages = self.getTotalPagesFromUrl(url,pageSize,headers=self.header)
        page = 1
        list=[]
        breakFlag = False
        while page<totalPages:
            rows =self.getRowsFromUrlByNoThread(url,page=page,pageSize=pageSize)
            temp=[]
            for o in rows:
                day = getDateTimeFromString(o["startTime"])
                if day<beginTime:
                    breakFlag = True
                    break
                if day>endTime:
                    continue
                temp.append(o)
            list.extend(temp)
            if breakFlag is True:
                break;
            page+=1
        print(list)
        for o in list:
            if o["maxReduce"] is None:
                o["maxReduce"]=o["reduce"]
        df  =pandas.DataFrame(list,columns=["id","startTime","endTime","name","reduce","maxReduce","useTime"])
#        df.to_excel("1.xlsx")
        total = df["id"].count()
        useCount = df["useTime"].isnull().sum()
        temp = "%s-%s" %(beginTime.strftime("%Y-%m-%d %H:%M:%S"),endTime.strftime("%Y-%m-%d %H:%M:%S"))
        temp += "\n发出：%s 已经使用：%s 未使用：%s" % (total,  int(total) - int(useCount),useCount)
        temp += "\n各种类型优惠券数量(%s):%s" % (
            total, str(df.groupby("name")["id"].count()).replace("name", "").replace("Name: id, dtype: int64", ""))
        temp += "\n各种类型优惠券金额(%s):%s" % (str(df["maxReduce"].sum()),
                                        str(df.groupby("name")["maxReduce"].sum()).replace("name", "").replace(
                                            "Name: maxReduce, dtype: float64", ""))
        print(temp)
        return temp

    def print_yestoday_user_counpon_info(self):
        return self.print_all_user_counpon_info(pageSize=100)

    def download_all_user_coupon(self, saveFileName="",beginTime=None,endTime=None, pageSize=50):

        if saveFileName.__eq__(""):
            saveFileName = self.getEnterpriseInfo()["name"]+" 所有会员优惠券.xlsx"
        if beginTime is None:
            now = datetime.datetime.now()
            beginTime = now+ datetime.timedelta(days=-1)
            print("beginTime = %s-%s-%s 00:00:00" % (beginTime.year, beginTime.month, beginTime.day))
            print("endTime = %s-%s-%s 23:59:59" %(beginTime.year,beginTime.month,beginTime.day))

            endTime = datetime.datetime.strptime("%s-%s-%s 23:59:59" %(beginTime.year,beginTime.month,beginTime.day), '%Y-%m-%d %H:%M:%S')
            beginTime = datetime.datetime.strptime("%s-%s-%s 00:00:00" %(beginTime.year,beginTime.month,beginTime.day), '%Y-%m-%d %H:%M:%S')
        else:
            beginTime = getDateTimeFromString(beginTime)
            endTime = getDateTimeFromString(endTime)


        url = "https://enterprise.aiyouzhan.cn/api/coupon/enterprise/coupon/page-list?token=%s&t=%s" % (
            self.token, int(time.time()))
        pageSize = 50
        totalPages = self.getTotalPagesFromUrl(url,pageSize,headers=self.header)
        page = 1
        list=[]
        breakFlag = False
        while page<totalPages:
            rows =self.getRowsFromUrlByNoThread(url,page=page,pageSize=pageSize)
            temp=[]
            for o in rows:
                day = getDateTimeFromString(o["startTime"])
                if day<beginTime:
                    breakFlag = True
                    break
                if day>endTime:
                    continue
                temp.append(o)
            list.extend(temp)
            if breakFlag is True:
                break;
            page+=1
        print(list)
        df  =pandas.DataFrame(list,columns=["startTime","endTime","name","reduce","useTime"])
        print(df.groupby("name")["reduce"].sum())
        df.to_excel(saveFileName)

    def getMemberRemoveList(self):
        baseUrl="https://enterprise.aiyouzhan.cn/api/member/enterprise/memberRemoveList?token=%s" %(self.token)
        rows=self.getRowsFromUrl(baseUrl,pageSize=50)
        pd =pandas.DataFrame(rows)
        pd.to_excel("%s_会员迁移数据.xlsx" % self.getEnterpriseInfo()["name"])
        print("OK")





    def download_user_coupon(self, saveFileName, pageSize=50):
        url = "https://api.aiyouzhan.cn/api/coupon/enterprise/coupon/page-list?token=%s&t=%s" % (
            self.token, int(time.time()))
        rows = self.getRowsFromUrl(url, pageSize=50)
        wb1, sheet = loadXlsGetSheel(saveFileName, '订单充值明细')

        titleArray = ['企业编号',
                      '加油站编号',
                      'i活动编号',
                      '用户编号',
                      '用户昵称',
                      '券号',
                      '优惠券名称',
                      '优惠券类型',
                      '允许赠送',
                      '满多少钱',
                      '是否开始',
                      '最大立减金额',
                      '会员等级',
                      'no',
                      '折扣额度%',
                      '减多少钱',
                      '活动开始时间',
                      '活动结束时间',
                      '皮肤',
                      '模板编号 ',
                      '使用时间',
                      '状态',
                      '描述',
                      ]
        i = 0
        for s in titleArray:
            sheet.cell(row=1, column=i + 1, value=s)
            i += 1
        row = 2
        pbar = tqdm(total=len(rows), desc="生成进度")
        for item in rows:
            sheet.cell(row=row, column=1, value=item['enterpriseId'])  # 企业编号
            sheet.cell(row=row, column=2, value=item['stationId'])  # 加油站编号
            sheet.cell(row=row, column=3, value=item['activityId'])  # i活动编号
            sheet.cell(row=row, column=4, value=item['userId'])  # 用户编号
            sheet.cell(row=row, column=5, value=item['username'])  # 用户昵称
            sheet.cell(row=row, column=6, value=item['id'])  # 券号
            sheet.cell(row=row, column=7, value=item['name'])  # 优惠券名称
            sheet.cell(row=row, column=8, value=item['type'])  # 优惠券类型
            sheet.cell(row=row, column=9, value=item['allowGiveAway'])  # 允许赠送
            sheet.cell(row=row, column=10, value=item['cost'])  # 满多少钱
            sheet.cell(row=row, column=11, value=item['isStart'])  # 是否开始
            sheet.cell(row=row, column=12, value=item['maxReduce'])  # 最大立减金额
            sheet.cell(row=row, column=13, value=item['needMember'])  # 会员等级
            sheet.cell(row=row, column=14, value=item['no'])  # no
            sheet.cell(row=row, column=15, value=item['percent'])  # 折扣额度%
            sheet.cell(row=row, column=16, value=item['reduce'])  # 减多少钱
            sheet.cell(row=row, column=17, value=item['startTime'])  # 活动开始时间
            sheet.cell(row=row, column=18, value=item['endTime'])  # 活动结束时间
            sheet.cell(row=row, column=19, value=item['style'])  # 皮肤
            sheet.cell(row=row, column=20, value=item['templateId'])  # 模板编号
            sheet.cell(row=row, column=21, value=item['useTime'])  # 使用时间
            sheet.cell(row=row, column=22, value=item['status'])  # 状态
            sheet.cell(row=row, column=23, value=item['description'])  # 描述

            row += 1
            pbar.update(1)
        pbar.close()
        wb1.save(saveFileName)
        print("采集用户优惠券完毕！")


def main():

    spider = AIYZSpider()
    spider.setToken("JGjlHBI7F0rPbGnrMjIxEDkdcNbX7cZS1T7BfZTbf6li/Uw6NbrXZPh0A2V/IoqgoYvb81yy/RGtaTLntPXkfR7ddtuoDr1Z5JuDtcOZf1INQbEGZ63xIVEEBT7ECiF1ti25Jr1Vc7t9nfcsSVhaPW6usamfTx1eeuEDUVvdgvKJfhXc1T4jo56mMhMDPYvGUmr8MKvHIcmrHq80Zog1nHvV2afM3aPIPItMj2fHIN8aL/5tEQZHojRdxtQ8B3yk2bzdBdl16m+b+xa6P9V6GmaSQEiehMKR4D4a3zjYPHWalwktezSxruM2ha6RJSrv+NM98KPyjnF/Tssp34BPwQ==")
    spider.searchOrderAndSaveToXls( size=100, status=2, operatorId='', oilTypeId='',
                                userId='', startDate="2021-05-10 00:00:00", endDate="2021-05-29 23:59:59")



if __name__ == '__main__':
   main()



